import React, { Component } from 'react';
import { View, Text, Image, StyleSheet, TouchableOpacity } from 'react-native';
import screen from './screen'
import system from './system'
import { RouteHelper } from 'react-navigation-easy-helper'
import ImageResources from './ImageResources'
import FetchResources from './FetchResources'
import Modal from 'antd-mobile/lib/modal'
import GetSetStorge from './GetSetStorge'
import DropDownMenu from './DropDownMenu'
import Popover from 'teaset/components/Popover/Popover'
import Overlay from 'teaset/components/Overlay/Overlay'
import axios from 'axios'
import qs from 'qs'
import Toast from 'antd-mobile/lib/toast'

const Alert = Modal.alert
class NavPage extends Component {

  constructor(props) {
    super(props)
    this.state = {
      isVisible: false,
      buttonRect: {},
    }
  }

  goBack() {
    this.props.goBack()
  }

  loginOut(){
    Alert('退出登录', '是否退出？', [
      { text: '取消', onPress: () => null },
      {
        text: '退出', onPress: this.out.bind(this) 
      },
    ])
  }

  out(){
    GetSetStorge.clearStorgeAsync()//清除所有缓存数据
    GetSetStorge.setStorgeAsync('isFrist', '')
    GetSetStorge.setStorgeAsync('sessionId', '')
    GetSetStorge.setStorgeAsync('loginInfo', '')
    RouteHelper.navigate('Splash',{showLogin:'true'})
  }

  _onPress(index) {
    this.overlayView && this.overlayView.close()
    if(index === 2){//退出登录
      this.loginOut()
    }else if(index === 1){//票务记录
      RouteHelper.navigate('Ticketing')
    }else if(index === 5){//退票
      RouteHelper.navigate('RefundTicket',{code:'',type:''})
    }else if(index === 3){

      //验证该账户是否有验票权限
      GetSetStorge.getStorgeAsync('loginInfo').then((result) => {
        if (result) {
          axios.post(FetchResources.Fetch.GetPermission,//获取当天权限和项目价格
            qs.stringify({
              sellerId:result.split('|')[0],
            })
          ).then((response) => {
            if(response.data.success){//登录成功
              let list = response.data.permissionList
              let inspectList = []
              if(list.length >= 1){
                for(let i=0 ; i<list.length ; i++){
                  if(list[i]['checkPermission'] == '1'){ //该用户对这个项目具有验票权限
                    inspectList.push(list[i])
                  }
                }
                if(JSON.stringify(inspectList) == '[]'){ // 没有验票权限 
                  Toast.fail('当前用户没有验票权限',0.5)
                  return 
                }
                if(inspectList.length > 1){
                  RouteHelper.navigate('InspectItem',{permissionList:JSON.stringify(inspectList)})
                }else if(inspectList.length == 1){
                  RouteHelper.navigate('InspectQuery',{consumptionName:inspectList[0]['consumptionName'],consumptionId:inspectList[0]['consumptionId']})
                }
              }else{
                Toast.fail('当前用户没有验票权限',0.5)
                return 
              }
  
            }
      
          }).catch((error) => {
            // alert(JSON.stringify(error))
            Toast.hide()
          })
        } 
      }).catch((error) => {
        console.log('==========================')
        console.log('系统异常' + error)
        console.log('==========================')
      })

    }else if(index === 4){
      RouteHelper.navigate('Print')
    }else if(index === 0){
      RouteHelper.navigate('App')
    }

  }

  _onDisappearCompleted() {

  }

  _onPressButton1(){
    // RouteHelper.navigate('Qrcode', {
    //   callBack: (ticketNumber) => {
    //    this.getTicketInfo(ticketNumber,'QRcode')
    //   }
    // })
    RouteHelper.navigate('Qrcode', {type:'refund'})
  }

  _onPressButton() {
    let {showInspect} = this.props
    Overlay.show(
      <Overlay.PopView
        ref={v => this.overlayView = v}
        onDisappearCompleted={this._onDisappearCompleted.bind(this)}
        style={[{ alignItems: 'flex-end',backgroundColor:'transparent',paddingRight:10 }, system.isIPhoneX ? { marginTop: 80 } : { marginTop: 60 }]}
      >
        <Popover style={[{ width: 170, borderRadius:5,paddingHorizontal:10 }]} arrow='topRight' paddingCorner={18}>
          <TouchableOpacity onPress={this._onPress.bind(this, 0)} activeOpacity={0.5}><View style={styles.dropDownList}><Text style={[styles.dropDownText]}>首页</Text></View></TouchableOpacity>
          {
            showInspect ? null :
            <TouchableOpacity onPress={this._onPress.bind(this, 3)} activeOpacity={0.5}><View style={styles.dropDownList}><Text style={styles.dropDownText}>验票</Text></View></TouchableOpacity>
          }

          {
            showInspect ? null :
            <TouchableOpacity onPress={this._onPress.bind(this, 5)} activeOpacity={0.5}><View style={styles.dropDownList}><Text style={styles.dropDownText}>退票</Text></View></TouchableOpacity>
          }
          

          <TouchableOpacity onPress={this._onPress.bind(this, 1)} activeOpacity={0.5}><View style={styles.dropDownList}><Text style={styles.dropDownText}>票务记录</Text></View></TouchableOpacity>
          <TouchableOpacity onPress={this._onPress.bind(this, 4)} activeOpacity={0.5}><View style={styles.dropDownList}><Text style={styles.dropDownText}>打印设置</Text></View></TouchableOpacity>
          <TouchableOpacity onPress={this._onPress.bind(this, 2)} activeOpacity={0.5}><View style={{height: 45,}}><Text style={styles.dropDownText}>注销</Text></View></TouchableOpacity>
        </Popover>
      </Overlay.PopView>
    );
  }


  render() {
    let {showGoBack,bgColor,refund} = this.props
    return (
      <View style={[styles.container,{backgroundColor:bgColor ?bgColor :'#E0E0E0'}]}>
        <View style={[{ alignItems: 'center', flex: 1, paddingTop: system.isIOS ? screen.screenTopInset : 20 }]}>
          {
            this.props.children ?
              this.props.children :
              <Text style={{ color: '#FFF', fontSize: 17 }}>{this.props.title}</Text>
          }
        </View>
        {showGoBack ?
        <TouchableOpacity style={[styles.item, styles.iconPosition]} onPress={this.goBack.bind(this)}>
          <Image style={styles.icon} source={ImageResources.CommonIcon['Back']} />
        </TouchableOpacity> : null
        }
        <View style={[styles.item, { position: 'absolute', right: 16, top: 12.5 + screen.screenTopInset, flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'flex-end', }]}>
          {/* <Image style={[styles.icon,{textAlign:'center'}]} source={ImageResources.CommonIcon['ArrowLeft']} /> */}
          {/* <Image style={styles.icon} source={ImageResources.CommonIcon['ArrowLeft']} /> */}
        </View>
        {
          refund ?
          <TouchableOpacity style={[styles.item, styles.iconPositionRight1]} onPress={this._onPressButton1.bind(this)}>
          {/* <Image style={styles.icon} source={ImageResources.CommonIcon['Setting']} /> */}
          <Text style={{ color: '#666',fontWeight:'600', fontSize: 17,textAlign:'center'}}>验/退票</Text>
          </TouchableOpacity> : null
        }
        


        <TouchableOpacity style={[styles.item, styles.iconPositionRight]} onPress={this._onPressButton.bind(this)}>
          <Image style={styles.icon} source={ImageResources.CommonIcon['Setting']} />
        </TouchableOpacity>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: (system.isIOS ? 0 : 15) + 50 + screen.screenTopInset,
    // backgroundColor: 'red',
    flexDirection: 'row',
    alignItems: 'center'
  },
  item: {
    width: screen.width / 3
  },
  center: {
    alignItems: 'center'
  },
  icon: {
    width: 21,
    height: 21
  },
  iconPosition: {
    position: 'absolute',
    width: 45,
    height: 45,
    left: 16,
    bottom: 0,
    justifyContent: 'center',
    paddingTop: system.isIOS ? 1 : 6
  },
  iconPositionRight: {
    position: 'absolute',
    width: 45,
    height: 45,
    right: 0,
    bottom: 0,
    justifyContent: 'center',
    paddingTop: system.isIOS ? 1 : 6
  },
  iconPositionRight1: {
    position: 'absolute',
    width:85,
    height: 45,
    right: 60,
    bottom: 0,
    justifyContent: 'center',
    paddingTop: system.isIOS ? 1 : 6
  },
  dropDownList:{
    borderBottomWidth:0.5,
    borderColor:'#ccc'
  },
  dropDownText:{
    paddingHorizontal: 10,
    textAlign:'center',
    fontSize:16,
    paddingVertical:14,
  }
})

NavPage.defaultProps = {
  goBack: function () { }
}
export default NavPage